import express from "express";
import AiImgModel from "../../../mongo/models/aiImg";
import path from "path";
import axios from "axios";
import fs from "fs";
import mongoose from "mongoose";
import { generateRandomKey } from "../../../utils/utils";
const { ObjectId } = mongoose.Types;

const router = express.Router();

const setImg = async (req: any, imageUrl: string) => {
  console.log(imageUrl);

  const id = req.jwtInfo.id;
  const IMG_FILE_PATH = path.join(__dirname, "../../../public/img/");
  // 创建和id相同的文件夹
  fs.mkdirSync(IMG_FILE_PATH + id, { recursive: true });
  // 随机文件名
  const pathEnd = id + "/" + generateRandomKey() + ".jpg";
  // 下载图片到文件夹
  const outputPath = IMG_FILE_PATH + pathEnd;
  //   生成十位数时间戳
  const timestamp = Math.floor(Date.now() / 1000);

  const x = `q-sign-algorithm=sha1&q-ak=AKIDPqaXAIbX8LJGHvOW26ExwOYQioWYIRYJTCKUUg_VIjgv9gBChjdFdzAkG7LPGLQW&q-sign-time=${timestamp};${
    timestamp + 1800
  }&q-key-time=${timestamp};${timestamp + 1800}&q-header-list=host&q-url-param-list=&q-signature=17aa5a9c979d0a4e47e9afcde7d3a4e53300b48d`;
  console.log(x);

  try {
    const response = await fetch("https://soujpg-private-1307121509.cos.ap-nanjing.myqcloud.com/ai-image/" + imageUrl, {
      headers: {
        accept: "*/*",
        "accept-language": "zh-CN,zh;q=0.9",
        authorization: x,
        "cache-control": "no-cache",
        pragma: "no-cache",
        "sec-ch-ua": '"Google Chrome";v="129", "Not=A?Brand";v="8", "Chromium";v="129"',
        "sec-ch-ua-mobile": "?0",
        "sec-ch-ua-platform": '"Windows"',
        "sec-fetch-dest": "empty",
        "sec-fetch-mode": "cors",
        "sec-fetch-site": "cross-site",
        "x-cos-security-token":
          "k0XPg3mn1VmsxMtRdU6bEakE4Myh2WOad80ada611e651bb7cd24723c6bf2c703_30YR6HAkaoAaOXt7MktQ8lNz-oydG_BINwTVyFTrbfNRqbIcIs2lT4bY3quElYbRP4oWVR-VsaJm0BfPbjf6DILv8IMm5bGznlhzaXbg9d9VI-H3RXxNARtXAC3O2OQ-rRMxE_vbHReXnIPawqpqswXNjdVkTAF_RFyaGxFfjXTo0BlvlyOXDLoBBj2X1rSiqwl-iQby_RE-qj_BvYoagYgVOadPRfWpx859Di1y08ECWAFIBhv8U7I_UtLTglwQo2eOiY1-z9NOFJJjH5r3zyLNZ2cxtEafElEJF663DKKa6lCayMD2QpMhimzYLU0f9k6Ik5Wwlh1Y6ii_AmrcHMSefe6H_qLz6P-nFIeiKI1dNx5EgGlXHvjDepzKDsztalakSY_y2yscUdOOgnh8w",
      },
      referrerPolicy: "no-referrer",
      body: null,
      method: "GET",
    });
    const buffer = await response.arrayBuffer();
    fs.writeFile(outputPath, Buffer.from(buffer), (err) => {
      if (err) {
        throw err;
      }
      console.log("Image downloaded successfully!");
    });
    // const response = await axios({
    //   method: "get",
    //   url: "https://soujpg-private-1307121509.cos.ap-nanjing.myqcloud.com/ai-image/" + imageUrl,
    //   headers: {
    //     accept: "*/*",
    //     "accept-language": "zh-CN,zh;q=0.9",
    //     authorization:
    //       "q-sign-algorithm=sha1&q-ak=AKIDLuvfc88Sa5Zh6kfdwC70qAvKbDOM1h8y0LTD9jDYeAMPzIk0Bm5atBMMnnWf7H3-&q-sign-time=1728551269;1728553069&q-key-time=1728551269;1728553069&q-header-list=host&q-url-param-list=&q-signature=66135cbf416ec86a6d6f7cef7bc590ee4584b684",
    //     "cache-control": "no-cache",
    //     pragma: "no-cache",
    //     "sec-ch-ua": '"Google Chrome";v="129", "Not=A?Brand";v="8", "Chromium";v="129"',
    //     "sec-ch-ua-mobile": "?0",
    //     "sec-ch-ua-platform": '"Windows"',
    //     "sec-fetch-dest": "empty",
    //     "sec-fetch-mode": "cors",
    //     "sec-fetch-site": "cross-site",
    //     "x-cos-security-token":
    //       "k0XPg3mn1VmsxMtRdU6bEakE4Myh2WOa236b4376e10717819503c3b59f6364d0_30YR6HAkaoAaOXt7MktQ3Ph7n5QwE0O3T-gy3Aei0iSko6WmPNyR5Fa6OIKIF-SwsVoXhuqBDW1LGSgD72XclWZ-KLjRfD9KKT4MwXPUjTG9qQVAXv_EdOylTy7d0nAMu3HUJiumtRXSy326KeLFMRt4M8YmTd6YxV8UcfJ1GJfKfPzS_jt7RP69qF11khredRKBunCY8Z-LLlvSyxGqDUuh_hjCbkA4EuqvZDaKB_DotYaIkPtnfJAupffDK3KQixQZ6g-u_tU3yrCSUJS1CLvc_LfOn1A67bbRZjZziMAYo2VMFIPqYI0BOy_zFP4O7eIZFIUKmZxd2-bhKrgFhgISuqakq_qmItexPAlzTzc3NF4AQtiYPFyApaYwnINCIP8lpqnI7uVqF1clDhcMQ",
    //   },
    //   referrerPolicy: "no-referrer",
    //     headers: {
    //       Host: "soujpg-private-1307121509.cos.ap-nanjing.myqcloud.com",
    //       Origin: "https://ai-acg.com",
    //       "X-Cos-Security-Token":
    //         "k0XPg3mn1VmsxMtRdU6bEakE4Myh2WOa78fd831a87ee035cd8accd2a14d1274b_30YR6HAkaoAaOXt7MktQxFqBwCS6UOvkQcwnGDq2KAo8MBPph4TeB-h05WSFdsuVlwqPpTmXIs3l5OjRPhguQ16FUswFSAZJqz7wUnbHEcZ_QQ5Y-oGp-5P5m6bPPpnmzkTzvAJkD3cmaC8VqWdN_vG9Uqt6Z19mUQN1erK4tTnFNI_NN3NyqaKl4PSfI_IMHXHdAFOEpUIPbBMmgrP3woMhBjVLVwrtfZGBOcB2-t6y8hntxQK1rTx6BUR4Kt1KsSrVd5RBPHDFdH2MnFRSozSTYScChbTl6LCMD-ny7nplSKchpoLH71y0A5pCHpqqVcbmNMGFU5oQQpF04SsWl8IiSGRpkg1AfpYwWMR5MBM-DApAqkhT_l6fquR-bmx4usI9sGwDniYeujeHfUaMA",
    //     //   Authorization: `q-sign-algorithm=sha1&q-ak=AKIDPqaXAIbX8LJGHvOW26ExwOYQioWYIRYJTCKUUg_VIjgv9gBChjdFdzAkG7LPGLQW&q-sign-time=${timestamp};${
    //     //     timestamp + 1800
    //     //   }&q-key-time=${timestamp};${timestamp + 1800}&q-header-list=host&q-url-param-list=&q-signature=17aa5a9c979d0a4e47e9afcde7d3a4e53300b48d`,
    //     },
    // });
    // response.data.pipe(fs.createWriteStream(outputPath));
    // return new Promise((resolve, reject) => {
    //   response.data.on("end", () => {
    //     AiImgModel.create({
    //       userName: req.jwtInfo.username,
    //       userId: req.jwtInfo.id,
    //       width: req.body.width || 540,
    //       height: req.body.height || 960,
    //       url: "public/img/" + pathEnd,
    //       desc: req.body.text,
    //       source: imageUrl,
    //     })
    //       .then((res) => {
    //         console.log(`保存成功`);
    //       })
    //       .catch((err) => {
    //         console.log(err);
    //       });
    //     resolve(`Image downloaded to ${outputPath}`);
    //   });
    //   response.data.on("error", (err: any) => {
    //     reject(err);
    //   });
    // });
  } catch (error) {
    console.error(`保存失败`, error);
  }
};

// 根据返回的 requestid 获取图片
async function getImg(req: any, requestId: string, token: string) {
  try {
    const data = await axios.get(
      `https://community-backend.soutushenqi.com/cykj_community/tools/processing?product_id=54&version_code=1016&requestId=${requestId}&processingPlatformType=AI_TOOL&processingType=TEXT2IMG&ref=AIACG_AI_DRAW&productType=AIACG&sign=04B1E702E1BB1EE1DD2FE3B6135C3D18`,
      {
        headers: {
          "Content-Type": "application/json",
          Token:
            "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE3NTk1NjQ0NDAsInByaW1hcnlLZXkiOiJ3YWxscGFwZXJfdG9rZW5fRm1meWU0NXhfNTQifQ.R51olYUtijREbHbal0V1TztcfIinZFqcR8RDXshywZ8",
        },
      }
    );

    if (data.data.generateStatus === "SUCCEEDED") {
      setImg(req, data.data.generatedImages[0]);
    } else {
      setTimeout(() => {
        let date = new Date();
        let formatter = new Intl.DateTimeFormat("zh-CN", {
          year: "numeric",
          month: "2-digit",
          day: "2-digit",
          hour: "2-digit",
          minute: "2-digit",
          second: "2-digit",
        });
        let formattedDate = formatter.format(date);

        if (data.data.generateStatus === "WAIT") {
          console.log(requestId, "排队中...", formattedDate);
        }
        if (data.data.generateStatus === "EXECUTING") {
          console.log(requestId, "图片生成中...", formattedDate);
        }

        getImg(req, requestId, token);
      }, 2000);
    }
  } catch (error) {
    // console.log(error);
  }
}

// 生成图片
router.post("/ai/img/create", async (req: any, res) => {
  let { text, modelName, token, width, height, path } = req.body;

  try {
    const data = await axios.post(
      "https://www.soujpg.com:8100/rest/image-search",
      {
        params: {
          token: token,
          width: 540,
          height: 960,
          userId: "3LcaP5rpheNrgpGb7qQh6F",
          prompt:
            "A girl with pink hair, four-headed proportions, half-body, exquisite five limbs, blue eyes, small round nose, long eyelashes, cherry hair, sea urchin, double horse tail, swimsuit",
          serviceMethod: "text2Image",
          guidance_scale: 7.5,
          returnType: "imageName",
          num_inference_steps: 30,
          asyncRequest: true,
          modelName: "meinamix_meinaV10",
          negative_prompt:
            "(worst quality),(low quality),(normal quality),lowres,nude,nipples,bad anatomy,bad hands,normal quality,(monochrome),(grayscale),low resolution, extra legs, mutated hands, fused fingers, watermark, vaguely, clitoris, extra hands, missing fingers, extra fingers, naked, dirt",
          schedulerName: "EulerAncestralDiscreteScheduler",
          ingoreTranslate: true,
          ingoreNsfw: true,
          ingoreSensitiveWordsCheck: true,
          loraParamses: [{ loraName: "Neoplasticism.safetensors", weight: 0.6 }],
        },
      },
      {
        headers: {
          "Content-Type": "application/json",
          Token:
            token ||
            "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE3NTk1NjQ0NDAsInByaW1hcnlLZXkiOiJ3YWxscGFwZXJfdG9rZW5fRm1meWU0NXhfNTQifQ.R51olYUtijREbHbal0V1TztcfIinZFqcR8RDXshywZ8",
        },
      }
    );
    getImg(req, data.data.asyncRequestId, token);
    res.send(data.data);
  } catch (error) {
    res.send({ code: 400, error: JSON.stringify(error) });
  }
});

// 获取图片
router.post("/ai/img/list", (req: any, res) => {
  const id = req.jwtInfo.id;
  let { page, size } = req.body;
  // 处理分页
  page = page || 1;
  size = size || 10;
  let skip = (page - 1) * size;

  const count = AiImgModel.countDocuments({ userId: id, del: false }).exec();
  //  倒序

  const data = AiImgModel.find({ userId: id, del: false }).sort({ _id: -1 }).select("_id url").limit(size).skip(skip).exec();

  Promise.all([count, data]).then(([count, data]) => {
    res.send({ code: 200, data: { count, data } });
  });
});

// 删除图片
router.post("/ai/img/del", (req: any, res) => {
  const id = req.jwtInfo.id;
  let { id: imgId } = req.body;
  const tempId = new ObjectId(imgId);
  AiImgModel.updateOne({ _id: tempId, userId: id }, { del: true })
    .then((data) => {
      res.send({ code: 200, data: data });
    })
    .catch((err) => {
      res.send({ code: 400, error: JSON.stringify(err), msg: { code: 400, msg: "删除失败" } });
    });
});

export default router;
